#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

#define STACK_INIT_SIZE 100 //初始化存储空间长度；
#define STACKINCREATEMENT 10 //每次增加空间的长度；
#define OK 1
#define ERROR 0
#define OVERFLOW -2

typedef int status;
typedef struct{
    int * top;
    int * base;
    int stacksize;
}sqstack;

//初始化
status initstack (sqstack *s)
{
    s.base=(int *)malloc(STACK_INIT_SIZE*sizeof(int));
    if (!s.base)
    {
        exit(OVERFLOW); 
    }
    s.top=s.base;
    s.stacksize=STACK_INIT_SIZE;
    return OK;
}

//销毁空栈
status destorystake(sqstack *s)
{
    if (s==NULL)//如果栈为空
    {
        return ERROR;
    }
    free(s->base);//释放基址空间
    free(s);//释放顺序栈
    s=NULL;//指针置空
    return OK;
}

//把栈置空
status clearstack(sqstack *s)
{
    if (s->base=NULL||s==NULL)
    {
        return ERROR;
    }
    s->top=s->base;//指针归位
    return OK;
}

//判断是否为空栈
status stackempty(sqstack s)
{
    if (s.base==NULL)
    {
        return ERROR;
    }
    if (s.base==s.top)
    {
        return true;
    }
    else return false;
}

//判断栈的长度
int stacklength(sqstack s)
{
    if (s.base==NULL)
    {
        return ERROR;
    }
    return (int)(s.top-s.base);
}

//返回到栈顶
status gettop(sqstack *s)
{
    int *re//用于保存要返回的数据
    if (s.top==s.base)
    {
        return NULL;
    }
    re=(s.top-1);
    return re;
}

//插入元素（入栈）
status push(sqstack *s,int e)
{
    if (s->top-s->base>=s->stacksize)//栈满
    {
        s.base=(int *)realloc(s.base,(s.stacksize+STACKINCREATEMENT)*sizeof(int));//增加存储空间
        if (!s->base)
        {
            exit(OVERFLOW);
        }
         s->top=s->base+s->stacksize;
         s->stacksize=s->stacksize+STACKINCREATEMENT;
    }
    s->top=e;
    s->top++;
    return OK;
}

//删除栈顶元素并返回
status pop(sqstack *s)
{
    int *re;
    if (s->top==s->base)
    {
        return NULL;
    }
    s->top=s->top-1;
    re=s->top;
    return re;
}

//查看栈中元素
status stacktraverse(sqstack *s,status(*visit)(int))
{
    if (s->base==NULL)
    {
        return ERROR;
    }
    int *tmp=s->base;
    for (int i = 0; tmp!=s->top; ++i)
    {
        visit(*tmp);
        tmp++;
    }
    return OK;
}